package convert;

import convert.types.ExcelToPdf;
import convert.types.ImageToPdf;
import convert.types.SlidesToPdf;
import convert.types.WordToPdf;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public class ConvertFactory {

    public static void toPdf(File file, OutputStream outputStream) throws IOException {
        Path path = file.toPath();
        String mimeType = Files.probeContentType(path);
        if (mimeType == null) {
            throw new RuntimeException("No content type found for " + file);
        }
        String fileName = path.getFileName().toString();
        if (mimeType.startsWith("image/")) {
            toPdf(Files.newInputStream(path), outputStream, FileFormat.IMAGE);
        } else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            toPdf(Files.newInputStream(path), outputStream, FileFormat.WORD);
        } else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
            toPdf(Files.newInputStream(path), outputStream, FileFormat.EXCEL);
        } else if (fileName.endsWith(".ppt") || fileName.endsWith(".pptx")) {
            toPdf(Files.newInputStream(path), outputStream, FileFormat.SLIDES);
        }
    }

    public static void toPdf(InputStream inputStream, OutputStream outputStream, FileFormat fileFormat) {
        try {
            if (fileFormat == FileFormat.IMAGE) {
                try (ConvertToPdf convert = new ImageToPdf(inputStream)) {
                    convert.toPdf(outputStream);
                }
            } else if (fileFormat == FileFormat.WORD) {
                try (ConvertToPdf convert = new WordToPdf(inputStream)) {
                    convert.toPdf(outputStream);
                }
            } else if (fileFormat == FileFormat.EXCEL) {
                try (ConvertToPdf convert = new ExcelToPdf(inputStream)) {
                    convert.toPdf(outputStream);
                }
            } else if (fileFormat == FileFormat.SLIDES) {
                try (ConvertToPdf convert = new SlidesToPdf(inputStream)) {
                    convert.toPdf(outputStream);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("convert image/word/excel/slides to PDF failed", e);
        }
    }
}
